/*
 * Copyright (c) Created by T C L on 2019.7.10.
 */

package cn.mumzone.pos.ui.dialog;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.event.BindMemberEntity;
import cn.mumzone.pos.model.SalesTimesCard;
import cn.mumzone.pos.presenter.TimesCardPurchasePresenter;
import cn.mumzone.pos.presenter.contract.TimesCardPurchaseContract;
import cn.mumzone.pos.ui.activity.ACT_SettleAccounts;
import cn.mumzone.pos.util.AddMemberUtil;
import cn.mumzone.pos.util.GoodsUtil;

public class TimesCardPurchaseDialogFragment extends DialogFragment implements TimesCardPurchaseContract.View {
    @BindView(R.id.tv_card_name)
    TextView tvCardName;
    @BindView(R.id.tv_card_des)
    TextView tvCardDes;
    @BindView(R.id.tv_card_total_times)
    TextView tvCardTotalTimes;
    @BindView(R.id.tv_card_last_time)
    TextView tvCardLastTime;
    @BindView(R.id.tv_applicable_items)
    TextView tvApplicableItems;
    @BindView(R.id.tv_period_of_validity)
    TextView tvPeriodOfValidity;
    @BindView(R.id.tv_total_times)
    TextView tvTotalTimes;
    @BindView(R.id.tv_card_price)
    TextView tvCardPrice;
    @BindView(R.id.rl_limit)
    RelativeLayout rlLimit;
    @BindView(R.id.tv_limit)
    TextView tvLimit;

    @BindView(R.id.btn_confirm_purchase)
    LoadingButton btnConfirmPurchase;

    private SalesTimesCard salesTimesCard;

    private TimesCardPurchasePresenter presenter;
    private String memberPhone;

    @Override
    public void onStart() {
        super.onStart();
        getDialog().setCanceledOnTouchOutside(false);//点击外部不消失
        // 设置SelectPicPopupWindow弹出窗体的背景
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        window.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));
        params.gravity = Gravity.CENTER;
        params.width = DisplayUtil.dip2px(getActivity(), 386);
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        salesTimesCard = (SalesTimesCard) getArguments().getSerializable("salesTimesCard");
        memberPhone = getArguments().getString("memberPhone");
        presenter = new TimesCardPurchasePresenter(getActivity(), this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_times_card_purchase, container, false);
        ButterKnife.bind(this, view);

        tvCardName.setText(salesTimesCard.getName());
        tvCardDes.setText(salesTimesCard.getServicesName());
        tvCardTotalTimes.setText(salesTimesCard.getTimes() + "次");
        tvCardLastTime.setText(String.format("有效期：%s个月", salesTimesCard.getValidDay()));

        rlLimit.setVisibility(GoodsUtil.isLimitTimeCard(salesTimesCard) ? View.VISIBLE : View.GONE);
        tvLimit.setText(GoodsUtil.isLimitTimeCard(salesTimesCard) ? getFormatLimitInfo(salesTimesCard) : "");

        tvApplicableItems.setText(salesTimesCard.getServicesName());
        tvPeriodOfValidity.setText(String.format("有效期：%s个月", salesTimesCard.getValidDay()));
        tvTotalTimes.setText(String.valueOf(salesTimesCard.getTimes()));
        tvCardPrice.setText("¥" + salesTimesCard.getOriginPrice());
        return view;
    }

    private String getFormatLimitInfo(SalesTimesCard salesTimesCard) {
        StringBuilder builder = new StringBuilder();
        if (!StringUtils.isEmpty(salesTimesCard.getUseExcludeDate()) && !"".equals(salesTimesCard.getUseExcludeDate())) {
            builder.append(salesTimesCard.getUseExcludeDate()).append("\n");
        }
        if (!ListUtil.isListEmpty(salesTimesCard.getTimeList())) {
            for (int index = 0; index < salesTimesCard.getTimeList().size(); index++) {
                SalesTimesCard.TimeListBean bean = salesTimesCard.getTimeList().get(index);
                builder.append(String.format("%s-%s", AppDateUtil.getDateToString(bean.getStartTime(), AppDateUtil.HH_MM),
                        AppDateUtil.getDateToString(bean.getEndTime(), AppDateUtil.HH_MM)));
                if (index < salesTimesCard.getTimeList().size() - 1) {
                    builder.append("或");
                }
            }
        }
        return builder.toString();
    }

    @OnClick(value = {R.id.iv_close, R.id.btn_confirm_purchase})
    public void toggleEvent(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.btn_confirm_purchase:
                btnConfirmPurchase.startLoading("确认购买");
                if (TextUtils.isEmpty(memberPhone)) {
                    AddMemberUtil.showSelectMemberDialog(getActivity(), presenter);
                } else {
                    showSearchMemberSuccess(memberPhone);
                }
                btnConfirmPurchase.stopLoading("确认购买");
                break;
        }
    }

    @Override
    public void showSearchMemberSuccess(String memberPhone) {
        //去购买
        JsonArray array = new JsonArray();
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("goodsId", salesTimesCard.getId());
        jsonObject.addProperty("goodsName", salesTimesCard.getName());
        jsonObject.addProperty("goodsCount", "1");
        jsonObject.addProperty("price", salesTimesCard.getPrice());
        jsonObject.addProperty("originPrice", salesTimesCard.getOriginPrice());
        array.add(jsonObject);
        ACT_SettleAccounts.startAc(getActivity(), memberPhone, array.toString(),
                ACT_SettleAccounts.SETTLE_ORDER_TYPE_TIMES_CARD, false);
        RxBus.getDefault().post(new BindMemberEntity());//传这个，关闭输入手机号的弹窗
        dismiss();
    }

}
